//
//  PUtil.m
//  iPiano
//
//  Created by wuxinting on 16/1/14.
//  Copyright © 2016年 wuxinting. All rights reserved.
//

#import "PUtil.h"

@implementation PUtil

// 拼接出url
+ (NSURL *)joinURL:(NSArray<NSString *> *)urls {
    if (!urls) {
        return nil;
    }
    
    NSMutableString *sUrl = [[NSMutableString alloc] initWithString:[urls objectAtIndex:0]];
    for (NSInteger i = 1; i < urls.count; i++) {
        NSString *url = [urls objectAtIndex:i];
        if (![url hasPrefix:@"/"] && ![sUrl hasSuffix:@"/"]) {
            [sUrl appendString:@"/"];
        }
        [sUrl appendString:url];
    }
    return [NSURL URLWithString:sUrl];
}

+ (NSString*)urlEncode:(NSString *)str {
    return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}

+ (NSString*)urlDecode:(NSString *)str {
    return [str stringByRemovingPercentEncoding];
}

+ (CGRect)shrinkRect:(CGRect)rect withRatio:(CGFloat)ratio {
    CGRect rRect = rect;
    rRect.size.width = rect.size.width * ratio;
    rRect.size.height = rect.size.height * ratio;
    rRect.origin.x = rect.size.width * (1 - ratio) / 2.0;
    rRect.origin.y = rect.size.height * (1 - ratio) / 2.0;
    return rRect;
}

+ (NSString*)pathWithoutExtension:(NSURL *)url {
    NSString *path = url.path;
    return [path stringByDeletingPathExtension];
}

@end

CGSize CGSizeInHWRatio(CGSize size, CGFloat ratio) {
    CGSize newSize = size;
    if (size.height > ratio * size.width) {
        newSize.height = ratio * size.width;
    } else {
        newSize.width = size.height / ratio;
    }
    return newSize;
}

inline CGRect CGRectCenterInSize(CGRect rect, CGSize size) {
    return CGRectMake((rect.size.width - size.width) / 2, (rect.size.height - size.height) / 2, size.width, size.height);
}

inline CGRect CGRectFromSize(CGSize size) {
    return CGRectMake(0, 0, size.width, size.height);
}
